package com.netty.clientserver.handler;

import cn.hutool.core.getter.ListTypeGetter;
import com.netty.clientserver.packet.Register;
import com.netty.clientserver.util.ConnectUtils;
import com.netty.common.entity.User;
import com.netty.common.enums.ExceptionEnum;
import com.netty.common.util.RedisUtil;
import io.netty.channel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ConnectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author LiuXiaoYu
 * @date 2022/2/3- 9:41
 */
@Service
@ChannelHandler.Sharable
public class NettyBindHandler extends SimpleChannelInboundHandler<Register> {

    /**
     * 通过前端传进来的token进行绑定
     * @param channelHandlerContext
     * @param register
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Register register) throws Exception {
        User user = register.getUser();
        if (Objects.isNull(user)){
            throw new RuntimeException(ExceptionEnum.ERROR.getDesc());
        }
        //绑定channel
        ConnectUtils.bindChannel(user,channelHandlerContext.channel());
        //通过groupChannel类型字段来判断是否是群聊channel
        if (register.getGroupChannel()){
            //说明是群聊channel 则获取grouopid
            Integer groupId = register.getToId();
            ConnectUtils.putGroupChannel(String.valueOf(groupId),channelHandlerContext.channel());
        }else {
            //说明是点对点私聊
            Integer toUserId = register.getToId();
            ConnectUtils.putPeerToPeerSingleChat(String.valueOf(user.getUserId()),String.valueOf(toUserId));
        }
        ConnectUtils.print();
        if (ConnectUtils.isBind(channelHandlerContext.channel())){
            System.out.println("用户:"+user.getUserId()+"绑定通道->channelId:"+channelHandlerContext.channel().id().asLongText()+",是否groupChannel:"+register.getGroupChannel());
        }
    }
}
